#!/bin/bash

echo "==================================="
echo "正在启动服务..."
echo "==================================="

# 检查 Java 环境
echo "检查 Java 环境..."
if ! command -v java &> /dev/null; then
    echo "错误: 未找到 Java，请先安装 Java"
    exit 1
fi

echo "检查 Java 版本..."
JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
echo "当前 Java 版本: $JAVA_VERSION"

# 提取主版本号
JAVA_MAJOR=$(echo $JAVA_VERSION | cut -d '.' -f 1)
if [ "$JAVA_MAJOR" -lt 17 ]; then
    echo "错误: 需要 Java 17 或更高版本"
    echo "请安装 Java 17 并设置 JAVA_HOME 环境变量"
    exit 1
fi

# 检查 Node.js 环境
echo "检查 Node.js 环境..."
if ! command -v node &> /dev/null; then
    echo "错误: 未找到 Node.js，请先安装 Node.js"
    exit 1
fi

# 检查 Maven 环境
echo "检查 Maven 环境..."
if ! command -v mvn &> /dev/null; then
    echo "错误: 未找到 Maven，请先安装 Maven"
    exit 1
fi

# 创建日志目录
echo "创建日志目录..."
mkdir -p logs

echo "==================================="
echo "启动 Node.js 服务..."
echo "==================================="
(
    cd ai-live-master-douyincast-node-service/dycast || exit
    echo "正在安装依赖..."
    npm install
    echo "启动 Node.js 服务..."
    export NODE_OPTIONS=--max_old_space_size=4096
    export PYTHONIOENCODING=utf-8
    export LANG=zh_CN.UTF-8
    nohup npm run dev > ../../logs/node-service.log 2>&1 &
)

echo "==================================="
echo "构建 Java 项目..."
echo "==================================="
echo "正在构建所有模块..."
export MAVEN_OPTS="-Dfile.encoding=UTF-8"
mvn clean install -Dmaven.test.skip=true -Dfile.encoding=UTF-8

echo "==================================="
echo "启动 Java 服务..."
echo "==================================="
if [ ! -f "ai-live-master-app/target/ai-live-master-app-1.0-SNAPSHOT.jar" ]; then
    echo "错误: 未找到 Java 服务 jar 包"
    echo "请确保 Maven 构建成功"
    exit 1
fi
(
    cd ai-live-master-app || exit
    export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF-8"
    nohup java -jar ./target/ai-live-master-app-1.0-SNAPSHOT.jar --spring.profiles.active=dev > ../logs/java-service.log 2>&1 &
)

echo "==================================="
echo "服务启动中，请稍候..."
echo "Node.js 服务将运行在: http://localhost:5173"
echo "Java 服务将运行在: http://localhost:8080/api/v1"
echo "日志文件位置:"
echo "- Node.js 日志: logs/node-service.log"
echo "- Java 日志: logs/java-service.log"
echo "==================================="

sleep 5
echo "如果服务没有正常启动，请检查日志文件"
